#!/bin/bash
#
# Make sure that old puppet cruft is removed
# This also allows us to downgrade puppet as
# it's more likely that installing old versions
# over new will cause issues.
#
# ${3} is the destination volume so that this works correctly
# when being installed to volumes other than the current OS.

<%- ["@apple_libdir", "@apple_sbindir", "@apple_bindir", "@apple_docdir", "@package_name"].each do |i| -%>
  <%- val = instance_variable_get(i) -%>
  <%- raise "Critical variable #{i} is unset!" if val.nil? or val.empty? -%>
<%- end -%>

# remove ruby library files. Because hiera and puppet both place a "hiera"
# directory in the libdir, we have to be sure we only delete the files
# belonging to this project. In this case, we only delete files from within
# the 'hiera' directory, while deleting the entire puppet directory.
<%- Dir.chdir("lib") do -%>
  <%- [@apple_old_libdir, @apple_libdir].compact.each do |libdir| -%>
    <%- Dir["hiera/**/*"].select{ |i| File.file?(i) }.each do |file| -%>
/bin/rm -f "${3}<%= libdir %>/<%= file %>"
    <%- end -%>
    <%- Dir.glob("*").each do |file| -%>
      <%- next if file == "hiera" -%>
      <%- if File.directory?(file) -%>
/bin/rm -Rf "${3}<%= libdir %>/<%= file %>"
      <%- else -%>
/bin/rm -f "${3}<%= libdir %>/<%= file %>"
      <%- end -%>
    <%- end -%>
  <%- end -%>
<%- end -%>

# remove bin files
<%- Dir.chdir("bin") do -%>
    <%- Dir.glob("*").each do |file| -%>
/bin/rm -f "${3}<%= @apple_bindir %>/<%= file %>"
  <%- end -%>
<%- end -%>

# remove old doc files
/bin/rm -Rf "${3}<%= @apple_docdir %>/<%= @package_name %>"

# These files used to live in the sbindir but were
# removed in Pupppet >= 3.0. Remove them
/bin/rm -f "${3}<%= @apple_sbindir %>/puppetca"
/bin/rm -f "${3}<%= @apple_sbindir %>/puppetd"
/bin/rm -f "${3}<%= @apple_sbindir %>/puppetmasterd"
/bin/rm -f "${3}<%= @apple_sbindir %>/puppetqd"
/bin/rm -f "${3}<%= @apple_sbindir %>/puppetrun"
